package com.service.lx;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dao.lx.DeptDAO;
import com.dao.lx.RoleDAO;
import com.dao.lx.UserDAO;
import com.entity.Dept;
import com.entity.Function;
import com.entity.Role;
import com.entity.User;
import com.service.ServiceException;
import com.utils.RoleFunctionItem;


@Service
@Transactional(rollbackFor = Exception.class)
public class UserService {
	@Autowired
	private UserDAO userDAO;
	@Autowired
	private RoleDAO roleDAO;
	@Autowired
	private DeptDAO deptDAO;
	/**
	 * 添加/修改/逻辑删除
	 * @param user
	 * @throws ServiceException
	 */
	public void addAndUpdateUser(User user) throws ServiceException{
		try {
			if(user.getDeptId()!=null){
				Dept dept=deptDAO.findOne(user.getDeptId());
				if(dept!=null){
					user.setDept(dept);
				}else{
					user.setDept(null);
				}
			}
			User user2=userDAO.findOne(user.getUserId());
			if(user2==null){
				user.setUserIfdelete(new BigDecimal(1));
			}
			user.setUserIntodate(new Date());
			userDAO.save(user);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 删除
	 * @param userid
	 * @throws ServiceException
	 */
	public void deleteUser(Long userid) throws ServiceException{
		try {
			userDAO.delete(userid);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 逻辑删除
	 * @param userId
	 */
	public void UpdateUserIfdelete(Long userId) {
		User user = userDAO.findOne(userId);
		user.setUserIfdelete(new BigDecimal(0));
		addAndUpdateUser(user);
	}
	
	/**
	 * 批量删除
	 * @param userIds
	 */
	public void deletArrIfDelete(List<Long> userIds) {
		if(userIds != null) {
			for(Long userId: userIds) {
				User user = userDAO.findOne(userId);
				user.setUserIfdelete(new BigDecimal(0));
				addAndUpdateUser(user);
			}
		}
	}
	/**
	 * 单条查询
	 * @param userid
	 * @return
	 */
	public User findOne(Long userid) {
		return userDAO.findOne(userid);
	}

	/**
	 * 查询所有
	 * @param curpage
	 * @param pagesize
	 * @return
	 */
	public Page<User> findAllUsers(Integer curpage, Integer pagesize){
		return userDAO.findAllUserIfdelete(new PageRequest(curpage-1, pagesize));
	}

	/**
	 * 查询用户名
	 * @param field
	 * @param curpage
	 * @param pagesize
	 * @return
	 */
	public Page<User> findByUid(String field, Integer curpage, Integer pagesize){
		return userDAO.findByUserUid(field, new PageRequest(curpage-1, pagesize));
	}
	
	/**
	 * 根据部门查询
	 * @param curpage
	 * @param pagesize
	 * @return
	 */
	public Page<User> findAllByDeptId(String field, Integer curpage, Integer pagesize){
		Dept dept=deptDAO.findOne(Long.parseLong(field));
		return userDAO.findByUserDept(dept,new PageRequest(curpage-1, pagesize));
	}
	/**
	 * 查询
	 * @param pagesize 页大小
	 * @return
	 */
	public Page<User> findUsersBy(String field, Integer curpage, Integer pagesize){
		String str;
		if(field.startsWith("uid")){
			str=field.replace("uid", "");
			return findByUid(str, curpage, pagesize);
		}else if(field.startsWith("dept")){
			str=field.replace("dept", "");
			return findAllByDeptId(str, curpage, pagesize);
		}else{
			return findAllUsers(curpage, pagesize);
		}
	}
	
	/**
	 * 获取所有角色
	 * @return
	 */
	public List<RoleFunctionItem> queryAllRoles(){
		List<Role> roles = (List<Role>) roleDAO.findAll();
		List<RoleFunctionItem> functionItems = new ArrayList<>();
		if(roles != null) {
			for(Role type: roles) {
				if(type.getRoleIfdelete().compareTo(BigDecimal.ZERO)==0){
					RoleFunctionItem item = new RoleFunctionItem(-type.getRoleId(), type.getRoleName(), true);
					functionItems.add(item);
				}else{
					RoleFunctionItem item2 = new RoleFunctionItem(type.getRoleId(), type.getRoleName(), false);
					functionItems.add(item2);
				}
			}
		}
		return functionItems;
	}
	
	/**
	 * 获取指定用户所拥有的角色id集合
	 * @param userId
	 * @return
	 */
	public List<Long> getRoleByUser(Long userId){
		User user = userDAO.findOne(userId);
		List<Role> role = user.getRoles();
		role.size();
		List<Long> list = new ArrayList<>();
		if(role != null) {
			for(Role r: role) {
				list.add(r.getRoleId());
			}
		}
		return list;
	}
	
	/**
	 * 赋给用户角色
	 * @param map
	 * @param functionIds
	 */
	public void grantForRole(Map map) {
		Integer userId = (Integer) map.get("userId");
		List<Long> roleIds = JSONObject.parseArray(((JSONArray) map.get("roleIds")).toString(), Long.class);
		User user = userDAO.findOne(userId.longValue());
		if(user.getRoles() != null) {
			user.getRoles().clear();
		}
		if(roleIds != null) {
			for(Long rid: roleIds) {
				Role role = roleDAO.findOne(rid);
				if(user.getRoles() != null) {
					user.getRoles().add(role);
				}
			}
		}
	}
	
	/**
	 * 获取指定用户拥有的功能
	 * @param userId
	 * @return
	 */
	public List<Long> getFunctionsByUserId(Long userId){
		User user = userDAO.findOne(userId);
		List<Long> list = new ArrayList<>();
		if(user != null) {
			List<Role> roles = user.getRoles();
			if(roles != null) {
				for(Role role: roles) {
					List<Function> functions = role.getFunctions();
					for(Function function: functions) {
						list.add(function.getFunctionId());
					}
				}
			}
		}
		return list;
	}
	
	/**
	 * 登陆
	 * @param userName
	 * @param password
	 * @return
	 */
	public User login(String userUid, String password) {
		User user = userDAO.login(userUid, password);
		if(user == null) return null; //登陆失败
		//判断是否有登陆权限
		List<Long> list = this.getFunctionsByUserId(user.getUserId());
		if(list.contains(1L)) {
			//有登陆权限
			return user;
		}else {
			//没有登陆权限
			return null;
		}
	}

	//查询用户名
	public User findUsersByUid(String userUid) {
		return userDAO.findByUserUid(userUid);
	}
}
